package com.origin.onlinesys.web.security.shiro.crypto;

import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;

/**
 *
 * Created by Administrator on 2015/1/23.
 * 计算密码匹配
 *
 */
public class CustomerHashService extends DefaultHashService {

    public CustomerHashService(){
        super();
        this.setHashAlgorithmName("SHA-512");
        this.setHashIterations(2);
        this.setGeneratePublicSalt(false);
        //设置私有盐
        this.setPrivateSalt(new SimpleByteSource("ORIGIN"));
    }


    /**
     * 计算hash值 DbAuthenticationRealm 调用
     * @param request
     * @return
     */
    public Hash computeHash(HashRequest request) {
        if (request == null || request.getSource() == null || request.getSource().isEmpty()) {
            return null;
        }

        //获取算法名字
        String algorithmName = getAlgorithmName(request);
        //转换为字节码
        ByteSource source = request.getSource();
        //迭代次数
        int iterations = getIterations(request);

        //随机生成的盐
//        ByteSource publicSalt = getPublicSalt(request);
        //私盐
        ByteSource salt = getPrivateSalt();

//        ByteSource salt = combine(privateSalt, publicSalt);

        SimpleHash result = new SimpleHash(algorithmName, source, salt, iterations);

       /* SimpleHash result = new SimpleHash(algorithmName);
        result.setBytes(computed.getBytes());
        result.setIterations(iterations);
        //Only expose the public salt - not the real/combined salt that might have been used:
        result.setSalt(salt);*/

        return result;
    }

}
